package com.store.practice.dto;

import com.store.practice.model.AppAccount;
import com.store.practice.model.UserPermission;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class AppUserDetails implements UserDetails {
    private AppAccount account;
    private List<UserPermission> permissions;

    public AppUserDetails(AppAccount account, List<UserPermission> permissions) {
        this.account = account;
        this.permissions = permissions;
    }

    public AppAccount getAccount() {
        return account;
    }

    public void setAccount(AppAccount account) {
        this.account = account;
    }

    public List<UserPermission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<UserPermission> permissions) {
        this.permissions = permissions;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return permissions.stream()
                .filter(userPermission -> userPermission.getValue()!=null)
                .map(userPermission -> new SimpleGrantedAuthority(userPermission.getValue()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return account.getPassword();
    }

    @Override
    public String getUsername() {
        return account.getPhone().toString();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
